﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;

namespace DISPLAY_CLIENT
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class ListWindow : Window
    {
        public class Record
        {
            public string staffno { get; set; }
            public string cardno { get; set; }
            public string name { get; set; }
            public string org { get; set; }
            public string job { get; set; }
            public string job_lev { get; set; }
            public DateTime intime { get; set; }
            public string inbeacon { get; set; }
            public DateTime outtime { get; set; }
            public string outbeacon { get; set; }
            public string duration { get; set; }
            public string InOut { get; set; }
            public string status { get; set; }
            public bool IsLocal { get; set; }
        }

        private ObservableCollection<Record> OutList = new ObservableCollection<Record>();
        private ObservableCollection<Record> InList = new ObservableCollection<Record>();
        private Queue<Record> RecQueue = new Queue<Record>();

        private MainWindow mainwnd;
        private InfoWindow infownd;

        Thread Refresh_Thread;

        public ListWindow(MainWindow parent)
        {
            InitializeComponent();
            mainwnd = parent;
            dg_list_out.ItemsSource = OutList;
            dg_list_in.ItemsSource = InList;
        }
       
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!mainwnd.ended)
            {
                if (Refresh_Thread != null)
                {
                    Refresh_Thread.Abort();
                    Refresh_Thread = null;
                    RecQueue.Clear();
                }
                if ((infownd != null) && (infownd.WindowState == WindowState.Normal))
                {
                    infownd.Close();
                }
                this.Hide();
                e.Cancel = true;
            }
            else
            {
                if (Refresh_Thread != null)
                {
                    Refresh_Thread.Abort();
                    Refresh_Thread = null;
                    RecQueue.Clear();
                }
                if ((infownd != null) && (infownd.WindowState == WindowState.Normal))
                {
                    infownd.Close();
                }
            }
        }

        private void Border_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                if (mainwnd.WindowState == WindowState.Maximized)
                {
                    mainwnd.WindowState = WindowState.Normal;
                    mainwnd.Height = SystemParameters.PrimaryScreenHeight * 0.9;
                    mainwnd.Width = SystemParameters.PrimaryScreenWidth * 0.9;
                }
                else
                {
                    mainwnd.WindowState = WindowState.Maximized;
                }
            }
        }

        private void Border_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                mainwnd.DragMove();
            }
        }

        private void btn_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //如果加载列表成功则显示窗口
        public void ShowData()
        {
            if (GetList())
            {
                this.Show();
                Refresh_Thread = new Thread(new ThreadStart(GetListChange));
                Refresh_Thread.IsBackground = true;
                Refresh_Thread.Start();
            }
            else
            {
                MessageBox.Show("数据库连接失败！", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //计算下井时长
        private string GetDuration(DateTime t1, DateTime t2)
        {
            TimeSpan ts;
            if (t2 > t1)
            {
                ts = t2 - t1;
            }
            else
            {
                ts = TimeSpan.Zero;
            }
            string str = string.Format("{0:00}小时{1:00}分", Math.Floor(ts.TotalHours), ts.Minutes);
            return str;
        }

        //根据本地消息更新列表
        private void UpdateList()
        {
            try
            {
                if (this.Visibility != Visibility.Visible)
                {
                    return;
                }

                while (RecQueue.Count > 0)
                {
                    Record NewRec = RecQueue.Dequeue();
                    GetRecord(NewRec.cardno, true);

                    if (NewRec.InOut == "0")
                    {
                        InList.Add(NewRec);
                    }
                    else if (NewRec.InOut == "1")
                    {
                        OutList.Add(NewRec);
                    }
                }
                
                lb_in.Content = "井下人员(" + InList.Count.ToString() + ")";
            }
            catch { }
        }

        //加载列表
        private bool GetList()
        {
            try
            {
                InList.Clear();
                OutList.Clear();
                DataTable dt = DB_SQLServer.ExecuteDataTable("SELECT ssf.STAFFNO,jt.TagMac,ssf.StaffName,sd.DEPTNAME,st.Typejobname,sp.PositionsName,IB.BeaconName InBea,PCA.InTime,OB.BeaconName OutBea,OutTime,ISWell,ud.intime FROM(SELECT*, ROW_NUMBER () OVER (PARTITION BY TagId ORDER BY	OutTime DESC) AS RN	FROM T_PP_UPDOWN) UD JOIN T_PP_CurrentArea pca ON pca.TagID = UD.TagId JOIN T_JC_Tag AS jt ON jt.TagID = UD.TagId JOIN T_SM_Staff AS ssf ON jt.StafffID = ssf.StaffID JOIN T_JC_Beacon IB ON IB.BeaconID = UD.InBeaconID JOIN T_JC_Beacon OB ON OB.BeaconID = UD.OutBeaconID LEFT JOIN SYS_DEPT AS sd ON ssf.DeptID = sd.DEPTID LEFT JOIN T_SM_TypeJob AS st ON ssf.TYPEJOB = st.TypeJobID LEFT JOIN T_SM_Position AS sp ON ssf.PositionsID = sp.PositionsID WHERE RN = 1 ORDER BY	OutTime DESC");

                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Record NewRec = new Record();
                        NewRec.staffno = dt.Rows[i][0].ToString();
                        NewRec.cardno = dt.Rows[i][1].ToString();
                        NewRec.name = dt.Rows[i][2].ToString();
                        NewRec.org = dt.Rows[i][3].ToString();
                        NewRec.job = dt.Rows[i][4].ToString();
                        NewRec.job_lev = dt.Rows[i][5].ToString();
                        if (dt.Rows[i][10].ToString() == "0")
                        {
                            NewRec.intime = Convert.ToDateTime(dt.Rows[i][7]);
                        }
                        else 
                        {
                            NewRec.intime = Convert.ToDateTime(dt.Rows[i][11]);
                        }
                        NewRec.inbeacon = dt.Rows[i][6].ToString();
                        if (NewRec.inbeacon.Length <= 0)
                        {
                            NewRec.inbeacon = "未知";
                        }
                        NewRec.outtime = Convert.ToDateTime(dt.Rows[i][9]);
                        NewRec.outbeacon = dt.Rows[i][8].ToString();
                        if (NewRec.outbeacon.Length <= 0)
                        {
                            NewRec.outbeacon = "未知";
                        }
                        NewRec.InOut = dt.Rows[i][10].ToString();
                        if (NewRec.InOut == "0")
                        {
                            NewRec.duration = GetDuration(NewRec.intime, DateTime.Now);
                            NewRec.status = "未出井";
                            InList.Add(NewRec);
                        }
                        else if (NewRec.InOut == "1")
                        {
                            NewRec.duration = GetDuration(NewRec.intime, NewRec.outtime);
                            NewRec.status = "已出井";
                            OutList.Add(NewRec);
                        }
                    }
                }

                lb_in.Content = "井下人员(" + InList.Count.ToString() + ")";

                return true;
            }
            catch 
            {
                return false;
            }
        }

        //根据数据库更新井下井上人员列表
        private void GetListChange()
        {
            while (true)
            {
                try
                {
                    while (RecQueue.Count > 0)
                    {
                        Thread.Sleep(1000);
                    }
                    DataTable dt = DB_SQLServer.ExecuteDataTable("SELECT ssf.STAFFNO,jt.TagMac,ssf.StaffName,sd.DEPTNAME,st.Typejobname,sp.PositionsName,IB.BeaconName InBea,PCA.InTime,OB.BeaconName OutBea,OutTime,ISWell,ud.intime FROM(SELECT*, ROW_NUMBER () OVER (PARTITION BY TagId ORDER BY	OutTime DESC) AS RN	FROM T_PP_UPDOWN) UD JOIN T_PP_CurrentArea pca ON pca.TagID = UD.TagId JOIN T_JC_Tag AS jt ON jt.TagID = UD.TagId JOIN T_SM_Staff AS ssf ON jt.StafffID = ssf.StaffID JOIN T_JC_Beacon IB ON IB.BeaconID = UD.InBeaconID JOIN T_JC_Beacon OB ON OB.BeaconID = UD.OutBeaconID LEFT JOIN SYS_DEPT AS sd ON ssf.DeptID = sd.DEPTID LEFT JOIN T_SM_TypeJob AS st ON ssf.TYPEJOB = st.TypeJobID LEFT JOIN T_SM_Position AS sp ON ssf.PositionsID = sp.PositionsID WHERE RN = 1 ORDER BY	OutTime DESC");
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            Record NewRec = new Record();
                            NewRec.staffno = dt.Rows[i][0].ToString();
                            NewRec.cardno = dt.Rows[i][1].ToString();
                            NewRec.name = dt.Rows[i][2].ToString();
                            NewRec.org = dt.Rows[i][3].ToString();
                            NewRec.job = dt.Rows[i][4].ToString();
                            NewRec.job_lev = dt.Rows[i][5].ToString();
                            if(dt.Rows[i][10].ToString() == "0")
                            {
                                NewRec.intime = Convert.ToDateTime(dt.Rows[i][7]);
                            }
                           else 
                            {
                                NewRec.intime = Convert.ToDateTime(dt.Rows[i][11]);
                            }
                            NewRec.inbeacon = dt.Rows[i][6].ToString();
                            if (NewRec.inbeacon.Length <= 0)
                            {
                                NewRec.inbeacon = "未知";
                            }
                            NewRec.outtime = Convert.ToDateTime(dt.Rows[i][9]);
                            NewRec.outbeacon = dt.Rows[i][8].ToString();
                            if (NewRec.outbeacon.Length <= 0)
                            {
                                NewRec.outbeacon = "未知";
                            }
                            NewRec.InOut = dt.Rows[i][10].ToString();
                            if (NewRec.InOut == "0")
                            {
                                NewRec.duration = GetDuration(NewRec.intime, DateTime.Now);
                                NewRec.status = "未出井";
                            }
                            else if (NewRec.InOut == "1")
                            {
                                NewRec.duration = GetDuration(NewRec.intime, NewRec.outtime);
                                NewRec.status = "已出井";
                            }

                            Record LastRec = GetRecord(NewRec.cardno, false);
                            if (LastRec == null)
                            {
                                RecQueue.Enqueue(NewRec);
                            }
                            else if (LastRec.outtime < NewRec.outtime)
                            {
                                RecQueue.Enqueue(NewRec);
                            }
                            else if ((NewRec.InOut == "0") && ((DateTime.Now - LastRec.outtime).TotalSeconds > 600))
                            {
                                NewRec.outtime = DateTime.Now;
                                RecQueue.Enqueue(NewRec);
                            }
                        }

                        if (RecQueue.Count > 0)
                        {
                            new Thread(() =>
                            {
                                this.Dispatcher.Invoke(new Action(this.UpdateList));
                            }).Start();
                        }

                        Thread.Sleep(1000);
                    }
                }
                catch { }
            }
        }

        //从列表中查找记录，再根据选项决定是否删除
        private Record GetRecord(string cardno,bool remove)
        {
            Record pos;
            pos = InList.FirstOrDefault(e => e.cardno == cardno);
            if (pos != null)
            {
                if (remove)
                {
                    InList.Remove(pos);
                }
                return pos;
            }
            pos = OutList.FirstOrDefault(e => e.cardno == cardno);
            if (pos != null)
            {
                if (remove)
                {
                    OutList.Remove(pos);
                }
                return pos;
            }
            return null;
        }

        //设置每行背景
        private void dg_list_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGridRow dataGridRow = e.Row;
            dataGridRow.Header = dataGridRow.GetIndex() + 1;
            dataGridRow.Foreground = Brushes.Black;
            dataGridRow.Background = Brushes.LightGoldenrodYellow;
        }

        //双击打开人员信息
        private void dg_list_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (sender != null)
            {
                DataGrid grid = sender as DataGrid;
                if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                {
                    Record SelRec = grid.SelectedItem as Record;
                    if ((SelRec.cardno.Length > 0) && (SelRec.staffno.Length > 0))
                    {
                        if ((infownd != null) && (infownd.WindowState == WindowState.Normal))
                        {
                            infownd.Close();
                        }
                        infownd = new InfoWindow(SelRec.cardno);
                        infownd.Height = this.Height;
                        infownd.Width = this.Width > 1600 ? this.Width / 4 : 400;
                        infownd.Show();
                    }
                }
            }
        }
    }
}
